'use client'

import { useEffect, useState } from 'react'
import { Card } from '@/components/ui/card'
import { ArrowDown, ArrowUp } from 'lucide-react'

interface MetricData {
  value: number
  dayOnDay?: number    // 同比昨日
  weekOnWeek?: number  // 同比上周
  monthOnMonth?: number // 环比上月
}

interface OverviewData {
  todayNewUsers: MetricData
  todayActiveUsers: MetricData
  weekNewUsers: MetricData
  monthNewUsers: MetricData
  yesterdayNewUsers: MetricData
  totalUsers: MetricData
}

const formatNumber = (num: number) => {
  return new Intl.NumberFormat('zh-CN').format(num)
}

const formatPercent = (num: number | string | null | undefined) => {
  if (num === undefined || num === null) return null
  const value = typeof num === 'string' ? parseFloat(num) : num
  if (isNaN(value)) return null
  return `${value > 0 ? '+' : ''}${value.toFixed(2)}%`
}

// 渲染增长率的组件
const GrowthRate = ({ 
  value, 
  label,
  showPlaceholder = true 
}: { 
  value: number | string | null | undefined
  label: string
  showPlaceholder?: boolean
}) => {
  const formattedValue = formatPercent(value)
  const numericValue = value ? (typeof value === 'string' ? parseFloat(value) : value) : 0
  
  if (!formattedValue && !showPlaceholder) return null
  
  return (
    <div className="flex items-center text-sm">
      <span className="text-gray-500 mr-2">{label}</span>
      {formattedValue ? (
        <span className={`flex items-center ${numericValue > 0 ? 'text-green-500' : 'text-red-500'}`}>
          {numericValue > 0 ? <ArrowUp className="w-3 h-3 mr-1" /> : <ArrowDown className="w-3 h-3 mr-1" />}
          {formattedValue}
        </span>
      ) : (
        <span className="text-gray-400">--</span>
      )}
    </div>
  )
}

interface Comparison {
  value: number | undefined
  label: string
  showPlaceholder?: boolean
}

interface Metric {
  title: string
  value: number
  comparisons: Comparison[]
}

export function UserMetricsOverview() {
  const [data, setData] = useState<OverviewData | null>(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true)
        setError(null)

        const today = new Date()
        const year = today.getFullYear()
        const month = (today.getMonth() + 1).toString().padStart(2, '0')
        const day = today.getDate().toString().padStart(2, '0')
        const dateStr = `${year}-${month}-${day}`

        const response = await fetch(
          `/api/overview?startDate=${dateStr}&endDate=${dateStr}`,
          {
            headers: {
              'Accept': 'application/json',
            }
          }
        )

        if (!response.ok) {
          throw new Error('获取数据失败')
        }

        const responseData = await response.json()
        setData(responseData)
      } catch (error) {
        console.error('Error fetching overview data:', error)
        setError(error instanceof Error ? error.message : '获取数据失败')
      } finally {
        setLoading(false)
      }
    }

    fetchData()
  }, [])

  if (error) {
    return (
      <div className="grid grid-cols-2 gap-8">
        <Card className="p-6 col-span-2 shadow-lg">
          <div className="text-red-500 text-center font-medium">{error}</div>
        </Card>
      </div>
    )
  }

  if (loading || !data) {
    return (
      <div className="grid grid-cols-2 gap-8">
        <Card className="p-6 col-span-2 shadow-lg">
          <div className="text-center font-medium">加载中...</div>
        </Card>
      </div>
    )
  }

  const metrics: Metric[] = [
    {
      title: '今日新增用户数',
      value: data.todayNewUsers.value,
      comparisons: [
        { value: data.todayNewUsers.dayOnDay, label: '较昨日' },
        { value: data.todayNewUsers.weekOnWeek, label: '较上周同期' }
      ]
    },
    {
      title: '今日活跃用户数',
      value: data.todayActiveUsers.value,
      comparisons: [
        { value: data.todayActiveUsers.dayOnDay, label: '较昨日' },
        { value: data.todayActiveUsers.weekOnWeek, label: '较上周同期' }
      ]
    },
    {
      title: '昨日新增用户数',
      value: data.yesterdayNewUsers.value,
      comparisons: [
        { value: data.yesterdayNewUsers.dayOnDay, label: '较前日' },
        { value: data.yesterdayNewUsers.weekOnWeek, label: '较上周同期' }
      ]
    },
    {
      title: '本周新增用户数',
      value: data.weekNewUsers.value,
      comparisons: [
        { value: data.weekNewUsers.weekOnWeek, label: '较上周同期' }
      ]
    },
    {
      title: '本月新增用户数',
      value: data.monthNewUsers.value,
      comparisons: [
        { value: data.monthNewUsers.monthOnMonth, label: '环比上月', showPlaceholder: false }
      ]
    },
    {
      title: '累计用户数',
      value: data.totalUsers.value,
      comparisons: [
        { value: data.totalUsers.monthOnMonth, label: '环比上月', showPlaceholder: false }
      ]
    }
  ]

  return (
    <div className="space-y-6 px-4 pt-4">
      <h3 className="text-xl font-semibold">用户分析</h3>
      <div className="grid grid-cols-3 gap-6">
        {metrics.map((metric, index) => (
          <Card key={index} className="p-6 shadow-sm hover:shadow-md transition-shadow duration-200">
            <div className="space-y-3">
              <div className="text-sm font-medium text-gray-600">{metric.title}</div>
              <div className="text-2xl font-bold text-gray-900">
                {formatNumber(metric.value)}
              </div>
              <div className="space-y-2 pt-3 border-t border-gray-100">
                {metric.comparisons.map((comparison, idx) => (
                  <GrowthRate
                    key={idx}
                    value={comparison.value}
                    label={comparison.label}
                    showPlaceholder={comparison.showPlaceholder !== false}
                  />
                ))}
              </div>
            </div>
          </Card>
        ))}
      </div>
    </div>
  )
} 